package data;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author Matthew Poulos
 * This class creates the network listening socket and listens in a thread
 */
public class NetworkListener implements Runnable {
    private ServerSocket serv;
    private DatabaseHandler db;

    public NetworkListener() {
        try {
            serv = new ServerSocket(4545);
            db = DatabaseHandler.getInstance();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * This method listens for data and inserts it into the database
     */
    public void run() {
        while (true) {
            try {
            	Socket clientSocket = serv.accept();
                DataInputStream in = new DataInputStream(clientSocket.getInputStream());
                
                while (true) {
                    /* Essentially the program reads until it gets to zero, which
                     * then throws an exception that is ignored.  The listener code
                     * works as far as I can tell.  I can disconnect and reconnect
                     * just fine  The code would be more elegant if the clientSocket.close
                     * would register
                     */
                    if (in.available() >= 0) {
                    	if (in.available() > 500) System.out.println(in.available());
                    	
                    	// Get number of samples
                    	int length = in.readUnsignedByte(); // Oops, wrote it down on board wrong, really is a byte

                        byte sensorID = in.readByte();
                        
                        //read in the values and times up to the length specified 
                        for(int i = 0; i < length; i++) {
                        	long time = in.readLong();
                        	int value = in.readUnsignedShort();
                        	
                        	insertDataPoint(sensorID, time, value);
                        }
                    }

                }
            } catch(EOFException e) {
                
            } catch (IOException e) {
                e.printStackTrace();
            } 
        }


    }

    private void insertDataPoint(byte sensorID, long time, int value) {
        db.insert(sensorID, time, value);
    }
    
    /*
     * This method is just used for debugging purposes
     *
    private static void printByteArray(byte[] b) {
        for (int i = 0; i < b.length; i++) {
            System.out.println("b[" + i + "]:\t" + b[i]);
        }
    }
    */
}
